package com.zeng.sim.support.server.socket;

import cn.hutool.core.lang.Pair;
import com.zeng.sim.util.ApplicationContextUtil;
import com.zeng.sim.util.SysConfigUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * 描述信息
 *
 * @author zengwanlin
 * @date 2023-12-25T13:53
 */
public class ServerSimSocketHandler implements Runnable {

    private static final Logger LOGGER = LoggerFactory.getLogger(ServerSimSocketHandler.class);

    private final Socket socket;

    public ServerSimSocketHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        if (socket == null) {
            LOGGER.warn("Socket为空");
            return;
        }

        try {
            String reqMsg = readMsg();

            ServerSimBusiProcessor processor = ApplicationContextUtil.getBean(ServerSimBusiProcessor.class);
            Pair<String, String> pair = processor.process(reqMsg);

            writeMsg(pair.getValue(), pair.getKey());
        }
        catch (IOException e) {
            LOGGER.error("模拟服务端-业务处理出错，" + e.getMessage(), e);
            // 可在此处返回通用错误报文
            throw new IllegalStateException("模拟服务端-业务处理出错，" + e.getMessage(), e);
        }
        finally {
            try {
                socket.close();
            }
            catch (IOException e) {
                LOGGER.warn("关闭Socket出错，" + e.getMessage(), e);
            }
        }
    }

    /**
     * 读取请求报文
     * @return
     * @throws IOException
     */
    private String readMsg() throws IOException {
        InputStream inputStream = socket.getInputStream();
        byte[] buf = new byte[512];
        int readLen = -1;

        ByteArrayOutputStream stream = new ByteArrayOutputStream(1024);

        while ((readLen = inputStream.read(buf)) != -1) {
            stream.write(buf, 0, readLen);
        }

        socket.shutdownInput();

        return stream
            .toString(SysConfigUtil.getSystemConfigValue(SysConfigUtil.CONFIG_CODE_SERVER_SIM_DEFAULT_CHARSET));
    }

    /**
     * 写出响应报文
     * @param respMsg
     * @param charsetName
     * @throws IOException
     */
    private void writeMsg(String respMsg, String charsetName) throws IOException {
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write(respMsg.getBytes(charsetName));
        outputStream.flush();

        socket.shutdownOutput();
    }

}
